﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;

public class DrawLine : MonoBehaviour {

	private LineRenderer lineRender;
	private float counter;
	private float dist;

	private Transform origin;
	private Transform destination;

	public float lineDrawSpeed = 6f;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {

		if (counter < dist) {
			counter += .1f / lineDrawSpeed;
			float x = Mathf.Lerp (0, dist, counter);

			Vector3 pointA = origin.position;
			Vector3 pointB = destination.position;

			Vector3 pointAlongLine = x * Vector3.Normalize (pointB - pointA) + pointA;

			lineRender.SetPosition (1, pointAlongLine);
		}
	}

	//Setup line render
	public void InitLineRender(Transform _origin, Transform _destination, bool checkAddCol = true)
	{
		origin = _origin;
		destination = _destination;
		lineRender = GetComponent<LineRenderer> ();
		lineRender.SetPosition (0, origin.position);
		lineRender.SetWidth (10f, 10f);

		dist = Vector3.Distance (origin.position, destination.position);

		if(checkAddCol)
			AddColliderToLine (lineRender, origin.position, destination.position);
	}


	private void AddColliderToLine(LineRenderer line, Vector3 startPos, Vector3 endPos)
	{
		GameObject obj = new GameObject ("Collider");
		ClickStraight straight = obj.AddComponent<ClickStraight> ();
		straight.InitClickStraight (gameObject);
		BoxCollider col = obj.AddComponent<BoxCollider> ();
		col.enabled = false;
		col.transform.parent = line.transform; // Collider is added as child object of line
		float lineLength = Vector3.Distance (startPos, endPos); // length of line
		col.size = new Vector3 (lineLength, 20f, 1f); // size of collider is set where X is length of line, Y is width of line, Z will be set as per requirement
		Vector3 midPoint = (startPos + endPos)/2;
		col.transform.position = midPoint; // setting position of collider object
		// Following lines calculate the angle between startPos and endPos
		float angle = (Mathf.Abs (startPos.y - endPos.y) / Mathf.Abs (startPos.x - endPos.x));
		if((startPos.y<endPos.y && startPos.x>endPos.x) || (endPos.y<startPos.y && endPos.x>startPos.x))
		{
			angle*=-1;
		}
		angle = Mathf.Rad2Deg * Mathf.Atan (angle);
		col.transform.Rotate (0, 0, angle);
	}
}
